package com.aracky.flowable.service.impl;

import com.aracky.common.util.FileUtil;
import com.aracky.common.vo.PageVO;
import com.aracky.flowable.model.request.StartFlowableRequest;
import com.aracky.flowable.service.ProcessService;
import com.aracky.flowable.utils.PageUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.image.ProcessDiagramGenerator;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zengzhiping
 * @BelongsPackage com.aracky.flowable.service.impl
 * @CreateTime 2022-08-17
 * @Description
 */
@Service
@DS("flowable")
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private HistoryService historyService;

    @Override
    public ResponseEntity<byte[]> genProcessDiagram(String processId) {

        // 获得当前活动的节点
        String processDefinitionId;
        // 如果流程已经结束，则得到结束节点
        if (this.isFinished(processId)) {
            HistoricProcessInstance pi = historyService.createHistoricProcessInstanceQuery().processInstanceId(processId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        } else {
            // 如果流程没有结束，则取当前活动节点
            // 根据流程实例ID获得当前处于活动状态的ActivityId合集
            ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
            processDefinitionId = pi.getProcessDefinitionId();
        }
        List<String> highLightedActivities = new ArrayList<>();

        // 获得活动的节点
        List<HistoricActivityInstance> highLightedActivityList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processId)
                .orderByHistoricActivityInstanceStartTime().asc().list();
        List<String> highLightedFlows = new ArrayList<>();

        for (HistoricActivityInstance tempActivity : highLightedActivityList) {
            String activityId = tempActivity.getActivityId();
            highLightedActivities.add(activityId);
            if ("sequenceFlow".equals(tempActivity.getActivityType())) {
                highLightedFlows.add(tempActivity.getActivityId());
            }
        }

        // 获取流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        ProcessEngineConfiguration engConf = processEngine.getProcessEngineConfiguration();
        ProcessDiagramGenerator processDiagramGenerator = engConf.getProcessDiagramGenerator();

        InputStream in = processDiagramGenerator.generateDiagram(bpmnModel, "png",
                highLightedActivities, highLightedFlows, engConf.getActivityFontName(),
                engConf.getLabelFontName(), engConf.getAnnotationFontName(), engConf.getClassLoader(),
                1.0, true);

        return FileUtil.showImage("流程图", in);
    }


    /**
     * 判断是否已完成
     *
     * @param processId
     * @return
     */
    private boolean isFinished(String processId) {
        ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processId).singleResult();
        //流程走完的不显示图
        if (pi == null) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }


    @Override
    public PageVO<Execution> executions(StartFlowableRequest flowableRequest) {
        //查询总数
        long count = runtimeService.createExecutionQuery().processDefinitionKey(flowableRequest.getProcessDefinitionKey()).count();
        //分页
        List<Execution> executionPages = runtimeService.createExecutionQuery().processDefinitionKey(flowableRequest.getProcessDefinitionKey())
                .listPage(flowableRequest.getPage() - 1, flowableRequest.getSize());
        //构造分页信息
        return PageUtil.buildPage(flowableRequest.getPage(), flowableRequest.getSize(), count, executionPages);
    }


    @Override
    public String deleteProcessInstanceById(String processInstanceId, String reason) {
        runtimeService.deleteProcessInstance(processInstanceId, reason);
        return "终止流程实例成功";
    }

    @Override
    public String handUpProcessInstance(String processInstanceId) {
        runtimeService.suspendProcessInstanceById(processInstanceId);
        return "挂起流程成功...";
    }

    @Override
    public String activateProcessInstance(String processInstanceId) {
        runtimeService.activateProcessInstanceById(processInstanceId);
        return "恢复流程成功...";
    }

    @Override
    public Boolean isExistProcIntRunning(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (processInstance == null) {
            return false;
        }
        return true;
    }

    @Override
    public List<HistoricProcessInstance> getMyStartProcint(String userId) {
        List<HistoricProcessInstance> list = historyService
                .createHistoricProcessInstanceQuery()
                .startedBy(userId)
                .orderByProcessInstanceStartTime()
                .asc()
                .list();
        return list;
    }


}
